package taskoauthproject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.appengine.api.users.UserServiceFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@SuppressWarnings("serial")
public class GoogleDriveServlet extends AbstractAppEngineAuthorizationCodeServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		resp.setContentType("text/html");
		
		Drive service = Utils.loadDriveService();
		
//		File body = new File();
//		
//		body.setTitle("Testovaci dokument");
//		body.setDescription("Popis dokumentu");
//		body.setMimeType("text/plain");
		
		
//		File newFile = service.files().insert(body).execute();
		
		
		String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
		
		resp.getWriter().println("UserId: " + userId);
		resp.getWriter().println("<br />");
		
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		
		String msgBody = "testovaci mail";
		
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("bartonek.lukas@gmail.com"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress("bartonek.lukas@gmail.com"));
			
			msg.setSubject("TEST");
			
			msg.setText(msgBody);
			
			Transport.send(msg);
		}
		catch (AddressException e) {
			System.out.println(e);
		}
		catch (MessagingException e) {
			System.out.println(e);			
		}
		
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		
		// Ziska seznam vsech souboru na Google Drive a vypise je do tabulky
		List<File> files = retrieveAllFiles(service);
		
		resp.getWriter().println(files.size());
		
		for(File file : files) {
			
			
			resp.getWriter().println("<table>");
				resp.getWriter().println("<tr>");
					resp.getWriter().println("<td>");
						resp.getWriter().println(file.getTitle());
					resp.getWriter().println("</td>");
					
					if (file.getAlternateLink() != null) {
						resp.getWriter().println("<td>");
							resp.getWriter().println("<a href=\"" + file.getAlternateLink() + "\">View</a>");
							
						resp.getWriter().println("</td>");
					}
					if (file.getDownloadUrl() != null) {
						resp.getWriter().println("<td>");
							resp.getWriter().println("<a href=\"" + file.getDownloadUrl() + "\">Download</a>");
							
						resp.getWriter().println("</td>");
					}
				resp.getWriter().println("</tr>");
			resp.getWriter().println("</table>");
		}
		
		
		
		
	
	}
	
	private static List<File> retrieveAllFiles(Drive service) throws IOException {
		
		List<File> result = new ArrayList<File>();
		Files.List request = service.files().list();
		
		do {
			
			try {
				
				FileList files = request.setMaxResults(5).setQ("sharedWithMe").execute();
				result.addAll(files.getItems());
				request.setPageToken(files.getNextPageToken());

			}
			catch (IOException e){
				System.out.println("error " + e);
				request.setPageToken(null);
			}
		} while (request.getPageToken() != null && (request.getPageToken().length() > 0));
		
		return result;
	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws ServletException,
			IOException {
		
		return Utils.newFlow();
	}

	@Override
	protected String getRedirectUri(HttpServletRequest req)
			throws ServletException, IOException {
		
		return Utils.getRedirectUri(req);
	}
}
